// 获取元素
const navCategoryHead = document.querySelector(".nav-category-head");
const category = document.querySelector(".category");

// 给一级菜单添加移入事件
navCategoryHead.addEventListener("mouseover", function () {
  category.style.display = "block";
});

// 添加移出事件
navCategoryHead.addEventListener("mouseleave", function () {
  category.style.display = "none";
});

category.addEventListener("mouseover", function () {
  category.style.display = "block";
});

category.addEventListener("mouseleave", function () {
  category.style.display = "none";
});

// 页面渲染

// 第多少页
let page = 1;

// 一个请求多少个数据
let number = 30;

// 定义一个变量
let goodsMsg = 0;

const pagerBigPager = document.querySelector('[name="sorter"]');

setPage();
async function setPage() {
  const urlObj = myGetUrlVal();
  // console.log(urlObj);
  if (urlObj.cateid === "undefined") {
    urlObj.cateid = localStorage.cateid;
  }
  const res = await pAjax({
    url: `/list?number=${number}&cateId=${urlObj.cateid}&page=${page}&sa=pc`,
    dataType: "json",
  });
  // console.log(res);

  // 把 res 赋值给 goodsMsg
  goodsMsg = res;

  // 把当前商品的商品 id 存入本地
  localStorage.cateid = urlObj.cateid;

  // 动态生成页面
  const goodsList = document.querySelector(".goods-list");

  let totalPages = Math.ceil(
    goodsMsg.data.totalNumber / number
  );

  let listStr = "";

  res.data.list.forEach(function (item) {
    listStr += `
    <li>
  <a href="./detail.html?goodsId=${item.goodsId}" class="pic">
    <img
      src="${item.picUrl}"
      alt="">
  </a>
  <div class="title">
    <a href="">${item.goodsName}</a>
  </div>
  <div class="price-bar clearfix">
    <span class="price">
      <em class="price-mark">¥</em>
      ${item.sellPrice}
    </span>
    <span class="shopping"></span>
  </div>
</li>
    `;
  });
  goodsList.innerHTML = listStr;

  let pageStr = `
  <div class="normal-page">
  <a href="javascript:;" class="page-item page-prev" name="prev">&lt;上一页</a>
  <span class="pageNumber">${page <= 1 ? 1 : page} / ${totalPages}</span>
  <a href="javascript:;" class="page-item page-next" name="next">下一页&gt;</a>
</div>
  `;

  pagerBigPager.innerHTML = pageStr;
}
 // 给 分页器的父元素添加事件委托
pagerBigPager.addEventListener("click", function (e) {
  // 如果点击的是 上一页
  if (e.target.getAttribute("name") === "prev") {
    
    if (page <= 1) return;
    page--;
    setPage();
    // 如果点击的是 下一页
  } else if (e.target.getAttribute("name") === "next") {
    let totalPages = Math.ceil(
      goodsMsg.data.totalNumber / number
    );
    if (page >= totalPages) return;
    page++;
    setPage();
  }
});
